const { sqlite3 } = require('../../mysql')


const hardwareCateList = async (ctx) => {
  let formData = ctx.query
  let offset = (formData.page - 1) * formData.limit
  let keyword = formData.query
  let limitdata = {}
  let data = {}
  if (keyword) {
    console.log('query:', keyword)
    limitdata = await sqlite3('category').where('name', 'LIKE', '%' + keyword + '%')
    .select()
    data = await sqlite3('category').where('name', 'LIKE', '%' + keyword + '%')
    .orderBy('id', 'desc').select().limit(formData.limit).offset(offset)
  } else {
    console.log('query1:', keyword)
    limitdata = await sqlite3('category').select()
    data = await sqlite3('category').orderBy('id', 'desc')
      .select().limit(formData.limit).offset(offset)
  }
  if (data) {
    ctx.body = {
      code: 200,
      item: data,
      total: limitdata.length
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

const hardwareCateCreate = async (ctx) => {
  console.log('ctx:', ctx.request.body)
  let formData = ctx.request.body
  const data = await sqlite3('category').insert(
    formData
  )
  console.log(data)
  if (data) {
    ctx.body = {
      code: 200,
      data: "success"
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

const hardwareCateUpdate = async (ctx) => {
  console.log('ctx:', ctx.request.body)
  let formData = ctx.request.body
  const data = await sqlite3('category')
    .where('id', formData.id)
    .update(formData)
  // console.log(data)
  if (data) {
    ctx.body = {
      code: 200,
      data: "success"
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

const hardwareCateDelete = async (ctx) => {
  console.log('ctx:', ctx.request.body)
  let formData = ctx.request.body
  const data = await sqlite3('category')
    .where('id', formData.id).del()
  console.log(data)
  if (data) {
    ctx.body = {
      code: 200,
      data: "success"
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}


module.exports = { hardwareCateList, hardwareCateCreate, hardwareCateUpdate, hardwareCateDelete }